from django.utils import timezone  # django转换UTC时间为本地时间
from kubernetes.client.rest import ApiException
from kubernetes import client


class OprationNamespacesApi():
    '''操作集群命名空间'''

    def __init__(self, namespace=None):
        self.namespace = namespace
        from kubernetes import config
        config.load_kube_config(config_file="./kube_conf/local.conf")
        self.coreApi_v1 = client.CoreV1Api()
        self.extensions_v1beta1 = client.ExtensionsV1beta1Api()

    def get_namespace_api(self):
        '''获取所有名称空间'''

        namespace_res = self.coreApi_v1.list_namespace(async_req=True)
        cluster = ['kube-public', 'default', 'kube-system', 'nginx-ingress']
        results = []
        for namespace in namespace_res.get().items:
            namespaces = {}
            if namespace.metadata.name not in cluster:
                namespaces['name'] = namespace.metadata.name
                namespaces['status'] = namespace.status.phase
                namespaces['create_time'] = timezone.localtime(namespace.metadata.creation_timestamp).strftime(
                    "%Y-%m-%d %H:%M:%S")
                results.append(namespaces)
        return results

    def create_namespace_api(self):
        '''创建命名空间'''

        namespaces = []
        namespace_res = self.coreApi_v1.list_namespace(async_req=True).get()
        for namespace in namespace_res.items:
            namespaces.append(namespace.metadata.name)
        if self.namespace in namespaces:
            return {'msg': '该空间已存在', 'results': self.get_namespace_api()}
        Body = client.V1Namespace(
            metadata=client.V1ObjectMeta(name=self.namespace)
        )
        try:
            namespace_res = self.coreApi_v1.create_namespace(body=Body, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': '创建失败,%s' % str(e)}
        else:
            return {'msg': str(namespace_res.status)}

    def delete_namespace_api(self):
        '''删除命名空间'''

        Body = client.V1DeleteOptions(
            propagation_policy='Foreground',
            grace_period_seconds=3
        )
        try:
            self.coreApi_v1.delete_namespace(name=self.namespace, body=Body, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': '删除失败,%s' % str(e)}
        else:
            return {'msg': '命名空间%s删除成功!' % self.namespace}
